package com.woke.addressactivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.bean.BaseResponse;
import com.bean.VipLevel;
import com.http.HttpMethods;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.woke.adapter.OnItemClickListener;
import com.woke.adapter.UpgradeMemberShipViewProvider;
import com.woke.diyview.PasswordView;
import com.woke.fragment.PwdAuthBottomSheetDialogFragment;
import com.woke.method.Md5jarss;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.BR;
import com.zhongcai.online.R;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * Created by Administrator on 2017/4/11 0011.
 * 会员升级
 */

public class UpgradeMemberShipActivity extends BaseListActivity implements XRecyclerView.LoadingListener  {

    private Items mItems = new Items();
    private MultiTypeAdapter mMulitypeAdapter;
    private Handler mHandler = new Handler();
    private MyApp mMyApp;
    private VipLevel mSelectedVipLevel;

    @Override
    public int getMenuId() {
        return 0;
    }

    @Override
    public boolean OnMenuItemClickListener(MenuItem item) {
        return false;
    }

    @Override
    public boolean OnNavigationClickListener() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding.setVariable(BR.base_list_title, getResources().getString(R.string.title_activity_upgrade_membership));
        mMyApp = MyApp.getInstance();
        initLayoutManagerAndProgressStyle();
        initVipUpdata();
        initMulitypeAdapter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initVipUpdata();
    }

    private void initVipUpdata() {
        Datas_load load = mMyApp.getDatas_load();
        if (load != null) {
            String userId = load.getId();
            if (!TextUtils.isEmpty(userId) && userId.matches("[0-9]*")) {
                HttpMethods.getInstance().getVipLevel(mVipLevelListObserver, Integer.parseInt(userId));
            }
        }
    }

    private Observer<List<VipLevel>> mVipLevelListObserver = new Observer<List<VipLevel>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<VipLevel> value) {
            if (value != null && value.size() > 0) {
                mItems.clear();
                mItems.addAll(value);
                if (mMulitypeAdapter != null) {
                    mMulitypeAdapter.notifyDataSetChanged();
                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                showToast(e.getMessage());
            }
        }

        @Override
        public void onComplete() {

        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    private void initMulitypeAdapter() {

        mMulitypeAdapter = new MultiTypeAdapter();
        mMulitypeAdapter.register(VipLevel.class, new UpgradeMemberShipViewProvider(mItemClickListener));
        mBinding.xRecyclerView.setAdapter(mMulitypeAdapter);
        mMulitypeAdapter.setItems(mItems);
        mMulitypeAdapter.notifyDataSetChanged();
//        if (mItems.size() > 0) {
//            assertAllRegistered(mMulitypeAdapter, mItems);//执行这句话时,必须保证 Items.size()>0
//        }
    }


    private OnItemClickListener mItemClickListener = new OnItemClickListener() {

        @Override
        public void OnItemClick(View view, int position) {

        }

        @Override
        public void OnItemClick(View view, Object object, int position) {
            if (object instanceof VipLevel) {
                mSelectedVipLevel = (VipLevel) object;
                showToast(mSelectedVipLevel.getVipdescribe());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Datas_load userInfo = mMyApp.getDatas_load();
                        if (userInfo != null) {
                            if (TextUtils.isEmpty(userInfo.getPay_pwd())) {
                                showToast("未设置支付密码");
                            } else {
                                passwordAuth();
                            }
                        }
                    }
                });
            }
        }
    };

    private void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(UpgradeMemberShipActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private PwdAuthBottomSheetDialogFragment mPwdAuthBottomSheet;

    private void passwordAuth() {
        if (mPwdAuthBottomSheet == null) {
            mPwdAuthBottomSheet = new PwdAuthBottomSheetDialogFragment();
            mPwdAuthBottomSheet.setAfterTextChangedListener(mAfterTextChangedListener);

        }
        mPwdAuthBottomSheet.show(getSupportFragmentManager(), "PwdAuthBottomSheet");
    }

    private OnItemClickListener mAfterTextChangedListener = new OnItemClickListener() {
        @Override
        public void OnItemClick(View view, int position) {

        }

        @Override
        public void OnItemClick(View view, Object object, int position) {
            if (view != null && view instanceof PasswordView) {
                CharSequence authPwd = (CharSequence) object;
                if (!TextUtils.isEmpty(authPwd)) {
                    String md5Password = Md5jarss.getMD5EncryptedStr(String.valueOf(authPwd));
                    Datas_load userInfo = mMyApp.getDatas_load();
                    if (userInfo != null) {
                        if (md5Password.equals(userInfo.getPay_pwd())) {
                            //升级会员 接口
                            String userId = userInfo.getId();
                            if (!TextUtils.isEmpty(userId) && userId.matches("[0-9]*")) {
                                HttpMethods.getInstance().memberUpApi(MemberUpObserver, Integer.parseInt(userId), mSelectedVipLevel.getViplevel());

                            }
                        } else {
                            showToast(getResources().getString(R.string.hint_enter_password_is_error));
                        }
                    } else {
                        showToast(getResources().getString(R.string.hint_un_sign_in_title));
                    }
                }
            }
        }
    };


    private Observer<BaseResponse> MemberUpObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {
            if (value != null) {
                if (value.resultSuccess()) {
                    EventBus.getDefault().post(new VipLevel());
//                    initVipUpdata();
                    new AlertDialog.Builder(UpgradeMemberShipActivity.this).setTitle("提示").setMessage(value.getInfo()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                         finish();
                        }
                    }).create().show();
                } else {
                    showToast(value.getInfo());
                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                showToast(e.getMessage());
            }
        }

        @Override
        public void onComplete() {

        }

    };
    @Override
    public void onRefresh() {
        initVipUpdata();
        mBinding.xRecyclerView.refreshComplete();

    }


}
